<?php
if(!defined('IN_SITE')) {
	exit('Access Denied');
}

class tools_crud{
	public $info_array = array();
	public $page_array = array();
	public $tree_array = array();

	static function &instance() {
		static $object;
		if(empty($object)) {
			$object = new self();
		}
		return $object;
	}

	/*
	*  添加
	*/
	public function add() {
        global $_G;
		$issubmit = isset($_REQUEST['issubmit']) && !empty($_REQUEST['issubmit']) ? $_REQUEST['issubmit']:'';
		if('1'==$issubmit){
            $tools_crud_add = isset($_REQUEST['tools_crud_add']) && !empty($_REQUEST['tools_crud_add']) ? $_REQUEST['tools_crud_add']:'';
            $tools_crud_position = isset($_REQUEST['tools_crud_position']) && !empty($_REQUEST['tools_crud_position']) ? $_REQUEST['tools_crud_position']:'';
            $tools_crud_position_dir = '';
            $tools_crud_position_pre = '';
            $tools_crud_setting_tpldir = $_G['setting']['tpldir'];
            if(1==$tools_crud_position){
               $tools_crud_position_dir=$_G['config']['admin_folder'].'/';
               $tools_crud_position_pre=$_G['config']['admin_folder'];
               $tools_crud_setting_tpldir = $_G['setting']['admin_tpldir'];
            }
            //DEBUG 数据空校验
            foreach($tools_crud_add AS $key => $value){
               if(empty($value)){
                   showmessage('操作失败,请正确填写信息','index.php?mod=tools&action=crud&do=add');
               }
            }
            //DEBUG 字段与字段名称 数量是否匹配
            $tools_crud_add['field_array']=explode(',',trim($tools_crud_add['field'],','));
            $tools_crud_add_count=count($tools_crud_add['field_array'])+2;
            $tools_crud_add['field_name_array']=explode(',',trim($tools_crud_add['field_name'],','));
            if(count($tools_crud_add['field_array']) != count($tools_crud_add['field_name_array'])){
                showmessage('操作失败,字段与名称不匹配','index.php?mod=tools&action=crud&do=add');
            }
            //DEBUG 判断数据表是否存在
            $table_name = $_G['config']['db']['1']['tablepre'].$tools_crud_add['mod'].'_'.$tools_crud_add['action'];
            $sql = "SHOW TABLES LIKE '". $table_name."'";
            $result = DB::fetch_all($sql);
            if(empty($result) && 1==2){
                showmessage('数据表名称不存在,请先创建数据表','index.php?mod=tools&action=crud&do=add');
            }else{
                //TODO 创建数据库 暂无字段类型的预定义与索引外键的界面处理,隐藏数据库暂由人工创建
                //showmessage('数据表名称已存在,请修改mod或action','index.php?mod=tools&action=crud&do=add');
                //DEBUG 生成模块的相关目录文件
                //DEBUG 创建class目录与文件
                $class_dir_path = SITE_ROOT.'./'.$tools_crud_position_dir.'source/class/'.$tools_crud_add['mod'];
                $class_file_path = $class_dir_path.'/'.$tools_crud_add['mod'].'_'.$tools_crud_add['action'].'.php';
                if(file_exists($class_file_path)){
                    showmessage($class_file_path.'文件已存在,请检查','index.php?mod=tools&action=crud&do=add');
                }else{
                    dmkdir($class_dir_path);
                    $src_file = SITE_ROOT.'./'.$tools_crud_position_dir.'source/module/tools/curd_files/source_class.php';
                    $target_file = $class_file_path;
                    $this->upload_file($src_file,$target_file);
                    //DEBUG 替换关键字标签
                    $target_file_content = @file_get_contents($target_file);
                    $target_file_content_new = str_replace(array('###tools_crud_add_mod###','###tools_crud_add_action###','###tools_crud_add_key###','###tools_crud_add_keyword###'),array($tools_crud_add['mod'],$tools_crud_add['action'],$tools_crud_add['key'],$tools_crud_add['keyword']),$target_file_content);
                    @file_put_contents($target_file,$target_file_content_new);
                }
                //DEBUG 创建module目录与文件
                $module_dir_path = SITE_ROOT.'./'.$tools_crud_position_dir.'source/module/'.$tools_crud_add['mod'];
                $module_file_path = $module_dir_path.'/'.$tools_crud_add['mod'].'_'.$tools_crud_add['action'].'.php';
                if(file_exists($module_file_path)){
                    showmessage($module_file_path.'文件已存在,请检查','index.php?mod=tools&action=crud&do=add');
                }else{
                    dmkdir($module_dir_path);
                    $src_file = SITE_ROOT.'./'.$tools_crud_position_dir.'source/module/tools/curd_files/source_module.php';
                    $target_file = $module_file_path;
                    $this->upload_file($src_file,$target_file);
                }
                //DEBUG 创建template目录与文件
                $template_dir_path = SITE_ROOT.'./'.$tools_crud_position_dir.'template/'.$tools_crud_setting_tpldir.'/'.$tools_crud_add['mod'].'/'.$tools_crud_add['action'];
                $template_file_add_path = $template_dir_path.'/'.'add.htm';
                if(is_dir($template_dir_path)){
                    showmessage($template_dir_path.'目录已存在,请检查','index.php?mod=tools&action=crud&do=add');
                }else{
                    dmkdir($template_dir_path);
                }
                if(file_exists($template_file_add_path)){
                    showmessage($template_file_add_path.'文件已存在,请检查','index.php?mod=tools&action=crud&do=add');
                }else{
                    //DEBUG 设置自定义显示字段 ###add_field###
                    $add_field = '';
                    $src_add_field_file = SITE_ROOT.'./'.$tools_crud_position_dir.'source/module/tools/curd_files/add_field.htm';
                    $src_add_field_content = @file_get_contents($src_add_field_file);
                    $tools_crud_add_add_field='';
                    if(!empty($tools_crud_add['field_array']) && !empty($tools_crud_add['field_name_array'])){
                        foreach($tools_crud_add['field_array'] AS $key => $value){
                            $tools_crud_add_add_field .= str_replace(array('###tools_crud_add_field###','###tools_crud_add_field_name###'),array($tools_crud_add['field_array'][$key],$tools_crud_add['field_name_array'][$key]),$src_add_field_content).PHP_EOL;
                        }
                    }
                    $src_file = SITE_ROOT.'./'.$tools_crud_position_dir.'source/module/tools/curd_files/add.htm';
                    $target_file = $template_file_add_path;
                    $this->upload_file($src_file,$target_file);
                    $target_file_content = @file_get_contents($target_file);
                    //DEBUG 替换自定义字段
                    $target_file_content_tmp = str_replace('###add_field###',$tools_crud_add_add_field,$target_file_content);
                    $target_file_content_new = str_replace(array('###tools_crud_add_name_var###','###tools_crud_add_mod###','###tools_crud_add_action###','###tools_crud_add_key###'),array($tools_crud_add['name_var'],$tools_crud_add['mod'],$tools_crud_add['action'],$tools_crud_add['key']),$target_file_content_tmp);
                    @file_put_contents($target_file,$target_file_content_new);
                }
                $template_file_edit_path = $template_dir_path.'/'.'edit.htm';
                if(file_exists($template_file_edit_path)){
                    showmessage($template_file_edit_path.'文件已存在,请检查','index.php?mod=tools&action=crud&do=add');
                }else{
                    //DEBUG 设置自定义显示字段 ###add_field###
                    $add_field = '';
                    $src_edit_field_file = SITE_ROOT.'./'.$tools_crud_position_dir.'source/module/tools/curd_files/edit_field.htm';
                    $src_edit_field_content = @file_get_contents($src_edit_field_file);
                    $tools_crud_add_edit_field='';
                    if(!empty($tools_crud_add['field_array']) && !empty($tools_crud_add['field_name_array'])){
                        foreach($tools_crud_add['field_array'] AS $key => $value){
                            $tools_crud_add_edit_field .= str_replace(array('###tools_crud_add_field###','###tools_crud_add_field_name###'),array($tools_crud_add['field_array'][$key],$tools_crud_add['field_name_array'][$key]),$src_edit_field_content).PHP_EOL;
                        }
                    }
                    $src_file = SITE_ROOT.'./'.$tools_crud_position_dir.'source/module/tools/curd_files/edit.htm';
                    $target_file = $template_file_edit_path;
                    $this->upload_file($src_file,$target_file);
                    $target_file_content = @file_get_contents($target_file);
                    $target_file_content_tmp = str_replace('###edit_field###',$tools_crud_add_edit_field,$target_file_content);
                    $target_file_content_new = str_replace(array('###tools_crud_add_name_var###','###tools_crud_add_mod###','###tools_crud_add_action###','###tools_crud_add_key###'),array($tools_crud_add['name_var'],$tools_crud_add['mod'],$tools_crud_add['action'],$tools_crud_add['key']),$target_file_content_tmp);
                    @file_put_contents($target_file,$target_file_content_new);
                }
                $template_file_index_path = $template_dir_path.'/'.'index.htm';
                if(file_exists($template_file_index_path)){
                    showmessage($template_file_index_path.'文件已存在,请检查','index.php?mod=tools&action=crud&do=add');
                }else{
                    $src_file = SITE_ROOT.'./'.$tools_crud_position_dir.'source/module/tools/curd_files/index.htm';
                    $target_file = $template_file_index_path;
                    $this->upload_file($src_file,$target_file);
                    $target_file_content = @file_get_contents($target_file);
                    //DEBUG 设置自定义显示字段
                    $tools_crud_add_field='';
                    if(!empty($tools_crud_add['field_array'])){
                        foreach($tools_crud_add['field_array'] AS $key => $value){
                            $tools_crud_add_field .='<td>{$value['.$value.']}</td>';
                        }
                    }
                    $tools_crud_add_field_name='';
                    if(!empty($tools_crud_add['field_name_array'])){
                        foreach($tools_crud_add['field_name_array'] AS $key => $value){
                            $tools_crud_add_field_name .='<th>'.$value.'</th>';
                        }
                    }
                    $target_file_content_new = str_replace(array('###tools_crud_add_name_var###','###tools_crud_add_mod###','###tools_crud_add_action###','###tools_crud_add_key###','###tools_crud_add_field###','###tools_crud_add_field_name###','###tools_crud_add_count###'),array($tools_crud_add['name_var'],$tools_crud_add['mod'],$tools_crud_add['action'],$tools_crud_add['key'],$tools_crud_add_field,$tools_crud_add_field_name,$tools_crud_add_count),$target_file_content);
                    @file_put_contents($target_file,$target_file_content_new);
                }
                //DEBUG 把创建模块插入到 系统菜单表 以便系统通过角色菜单控制 把菜单分配给用户
                $common_menu_index = array(
                    'menu_pid'=>$tools_crud_add['menu_pid'],
                    'cm_mod'=>$tools_crud_add['mod'],
                    'cm_action'=>$tools_crud_add['action'],
                    'cm_do'=>'index',
                    'position'=>$tools_crud_position_pre.'_'.$tools_crud_add['mod'].'_'.$tools_crud_add['action'].'_index',
                    'name_var'=>$tools_crud_add['name_var'],
                    'url'=>'index.php?mod='.$tools_crud_add['mod'].'&action='.$tools_crud_add['action'].'&do=index',
                    'create_dateline'=>TIMESTAMP
                );
                $common_menu_index_menu_id=@DB::insert('common_menu',$common_menu_index,true);
                if($common_menu_index_menu_id){
                    //DEBUG 赋予后台管理员 新建模块菜单 访问权限
                    @DB::insert('user_role_menu',array('menu_id'=>$common_menu_index_menu_id,'role_id'=>3));
                }
                //DEBUG 添加列表菜单
                $common_menu_list=$common_menu_index;
                $common_menu_list['menu_pid'] = $common_menu_index_menu_id;
                $common_menu_list['cm_do'] = 'index';
                $common_menu_list['position'] = $tools_crud_position_pre.'_'.$tools_crud_add['mod'].'_'.$tools_crud_add['action'].'_'.$common_menu_list['cm_do'];
                $common_menu_list['name_var'] = $tools_crud_add['name_var'].'列表';
                $common_menu_list['url'] = 'index.php?mod='.$tools_crud_add['mod'].'&action='.$tools_crud_add['action'].'&do='.$common_menu_list['cm_do'];
                $common_menu_list_menu_id=@DB::insert('common_menu',$common_menu_list,true);
                if($common_menu_list_menu_id){
                    //DEBUG 赋予后台管理员 新建模块菜单 访问权限
                    @DB::insert('user_role_menu',array('menu_id'=>$common_menu_list_menu_id,'role_id'=>3));
                }
                //DEBUG 添加add菜单
                $common_menu_add=$common_menu_index;
                $common_menu_add['menu_pid'] = $common_menu_index_menu_id;
                $common_menu_add['cm_do'] = 'add';
                $common_menu_add['name_var'] = '添加'.$tools_crud_add['name_var'].'';
                $common_menu_add['position'] = $tools_crud_position_pre.'_'.$tools_crud_add['mod'].'_'.$tools_crud_add['action'].'_'.$common_menu_add['cm_do'];
                $common_menu_add['url'] = 'index.php?mod='.$tools_crud_add['mod'].'&action='.$tools_crud_add['action'].'&do='.$common_menu_add['cm_do'];
                $common_menu_add_menu_id=@DB::insert('common_menu',$common_menu_add,true);
                if($common_menu_add_menu_id){
                    //DEBUG 赋予后台管理员 新建模块菜单 访问权限
                    @DB::insert('user_role_menu',array('menu_id'=>$common_menu_add_menu_id,'role_id'=>3));
                }
                //DEBUG 添加edit菜单
                $common_menu_edit=$common_menu_index;
                $common_menu_edit['menu_pid'] = $common_menu_index_menu_id;
                $common_menu_edit['cm_do'] = 'edit';
                $common_menu_edit['name_var'] = '编辑'.$tools_crud_add['name_var'].'';
                $common_menu_edit['position'] = $tools_crud_position_pre.'_'.$tools_crud_add['mod'].'_'.$tools_crud_add['action'].'_'.$common_menu_edit['cm_do'];
                $common_menu_edit['url'] = 'index.php?mod='.$tools_crud_add['mod'].'&action='.$tools_crud_add['action'].'&do='.$common_menu_edit['cm_do'];
                $common_menu_edit['enable'] = 0;
                $common_menu_edit_menu_id=@DB::insert('common_menu',$common_menu_edit,true);
                if($common_menu_edit_menu_id){
                    //DEBUG 赋予后台管理员 新建模块菜单 访问权限
                    @DB::insert('user_role_menu',array('menu_id'=>$common_menu_edit_menu_id,'role_id'=>3));
                }
                //DEBUG 添加delete菜单
                $common_menu_delete=$common_menu_index;
                $common_menu_delete['menu_pid'] = $common_menu_index_menu_id;
                $common_menu_delete['cm_do'] = 'delete';
                $common_menu_delete['name_var'] = '删除'.$tools_crud_add['name_var'].'';
                $common_menu_delete['position'] = $tools_crud_position_pre.'_'.$tools_crud_add['mod'].'_'.$tools_crud_add['action'].'_'.$common_menu_delete['cm_do'];
                $common_menu_delete['url'] = 'index.php?mod='.$tools_crud_add['mod'].'&action='.$tools_crud_add['action'].'&do='.$common_menu_delete['cm_do'];
                $common_menu_delete['enable'] = 0;
                $common_menu_delete_menu_id=@DB::insert('common_menu',$common_menu_delete,true);
                if($common_menu_delete_menu_id){
                    //DEBUG 赋予后台管理员 新建模块菜单 访问权限
                    @DB::insert('user_role_menu',array('menu_id'=>$common_menu_delete_menu_id,'role_id'=>3));
                }
                //TODO 校验创建的模块相关文件是否存在 以便校验模块及功能是否创建成功
                updatecache('setting');
                showmessage('操作成功','index.php?mod=tools&action=crud&do=add');
            }
		}else{
			include template('tools/crud/add');
		}
	}
    
	/*
	*  删除
	*/
	public function delete() {
        global $_G;
		$issubmit = isset($_REQUEST['issubmit']) && !empty($_REQUEST['issubmit']) ? $_REQUEST['issubmit']:'';
		$tools_crud_delete = isset($_REQUEST['tools_crud_delete']) && !empty($_REQUEST['tools_crud_delete']) ? $_REQUEST['tools_crud_delete']:'';
        $tools_crud_position = isset($_REQUEST['tools_crud_position']) && !empty($_REQUEST['tools_crud_position']) ? $_REQUEST['tools_crud_position']:'';
        $tools_crud_position_dir = '';
        $tools_crud_position_pre = '';
        $tools_crud_setting_tpldir = $_G['setting']['tpldir'];
        if(1==$tools_crud_position){
           $tools_crud_position_dir=$_G['config']['admin_folder'].'/';
           $tools_crud_position_pre=$_G['config']['admin_folder'];
           $tools_crud_setting_tpldir = $_G['setting']['admin_tpldir'];
        }
		if('1'==$issubmit){
            //DEBUG 删除生成模块的相关目录文件
            if(empty($tools_crud_delete['action']) && !empty($tools_crud_delete['mod'])){
                //DEBUG 删除模块目录
                $class_dir_path = realpath(SITE_ROOT.'./'.$tools_crud_position_dir.'source/class/'.$tools_crud_delete['mod']);
                $module_dir_path = realpath(SITE_ROOT.'./'.$tools_crud_position_dir.'source/module/'.$tools_crud_delete['mod']);
                $template_dir_path = realpath(SITE_ROOT.'./'.$tools_crud_position_dir.'template/'.$tools_crud_setting_tpldir.'/'.$tools_crud_delete['mod']);
                @rmkdir($class_dir_path);
                @rmkdir($module_dir_path);
                @rmkdir($template_dir_path);
                //DEBUG 判断文件是否存在 删除是否成功
                if(is_dir($class_dir_path)){
                    showmessage($class_dir_path.'删除失败,请确定是否有权限删除','index.php?mod=tools&action=crud&do=delete');
                }
                if(is_dir($module_dir_path)){
                    showmessage($module_dir_path.'删除失败,请确定是否有权限删除','index.php?mod=tools&action=crud&do=delete');
                }
                if(is_dir($template_dir_path)){
                    showmessage($template_dir_path.'删除失败,请确定是否有权限删除','index.php?mod=tools&action=crud&do=delete');
                }
                //TODO 取出删除待删除的菜单编号 并删除菜单关系
                @DB::delete('common_menu',array('cm_mod'=>$tools_crud_delete['mod']));
                updatecache('setting');
                showmessage('操作成功','index.php?mod=tools&action=crud&do=delete');
            }elseif(!empty($tools_crud_delete['action']) && !empty($tools_crud_delete['mod'])){
                //DEBUG 删除模块功能文件与其模板目录
                $class_dir_path = SITE_ROOT.'./'.$tools_crud_position_dir.'source/class/'.$tools_crud_delete['mod'];
                $module_dir_path = SITE_ROOT.'./'.$tools_crud_position_dir.'source/module/'.$tools_crud_delete['mod'];
                $class_file_path = $class_dir_path.'/'.$tools_crud_delete['mod'].'_'.$tools_crud_delete['action'].'.php';
                $module_file_path = $module_dir_path.'/'.$tools_crud_delete['mod'].'_'.$tools_crud_delete['action'].'.php';
                $template_dir_path = SITE_ROOT.'./'.$tools_crud_position_dir.'template/'.$tools_crud_setting_tpldir.'/'.$tools_crud_delete['mod'].'/'.$tools_crud_delete['action'];
                @unlink($class_file_path);
                @unlink($module_file_path);
                @rmkdir($template_dir_path);
                //DEBUG 判断文件是否存在 删除是否成功
                if(file_exists($class_file_path)){
                    showmessage($class_file_path.'删除失败,请确定是否有权限删除','index.php?mod=tools&action=crud&do=delete');
                }
                if(file_exists($module_file_path)){
                    showmessage($module_file_path.'删除失败,请确定是否有权限删除','index.php?mod=tools&action=crud&do=delete');
                }
                if(is_dir($template_dir_path)){
                    showmessage($template_dir_path.'删除失败,请确定是否有权限删除','index.php?mod=tools&action=crud&do=delete');
                }
                //TODO 取出删除待删除的菜单编号 并删除菜单关系
                //DEBUG 自动删除模块功能对应的菜单
                @DB::delete('common_menu',array('cm_mod'=>$tools_crud_delete['mod'],'cm_action'=>$tools_crud_delete['action']),1);
                updatecache('setting');
                showmessage('操作成功','index.php?mod=tools&action=crud&do=delete');
            }else{
                showmessage('非法操作','index.php?mod=tools&action=crud&do=delete');
            }
		}else{
			include template('tools/crud/delete');
		}
    }
    
	/*
	*  文件移动处理
	*/
    private function upload_file($src_file,$target_file){
        @copy($src_file,$target_file);
        if(!file_exists($target_file) && function_exists('move_uploaded_file'))
        {
            @move_uploaded_file($src_file,$target_file);
        }
        if(!file_exists($target_file))
        {
            if (@is_readable($src_file) && (@$fp_s = fopen($src_file, 'rb')) && (@$fp_t = fopen($target_file, 'wb'))) {
                while (!feof($fp_s)) {
                    $s = @fread($fp_s, 1024 * 512);
                    @fwrite($fp_t, $s);
                }
                fclose($fp_s); fclose($fp_t);
            }
        }
    }
}
?>